package com.ruben.jwtdemo.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.ruben.jwtdemo.pojo.User;
import com.ruben.jwtdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: LoginInterceptor
 * @Description:
 * @Date: 2020/8/23 11:19
 * *
 * @author: achao<achao1441470436 @ gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置编码格式
        response.setContentType("text/html;charset=UTF-8");
        // 从request中获取token
        String token = userService.getToken(request);
        User user = null;
        if (StringUtils.isNotBlank(token)) {
            // 如果token不为空，校验token并获取用户
            user = userService.verifyToken(token);
        }
        if (user == null) {
            // 如果未查询到用户，说明校验失败，返回登录提示
            R<?> result = R.failed("请登录").setCode(402);
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        return true;
    }
}
